/*
    TwoPageView image viewer
    Copyright (C) 2006 Japan Manoretimedia Lab.

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
using System;
using System.Collections.Generic;
using System.Text;

namespace TwoPageView
{
    public enum DocumentArrangeDirection
    {
        RightToLeft,
        LeftToRight,
    };
    public enum PageViewModeSelection
    {
        AutoSelect,
        Always1Page,
        Always1PageHorizontal,
        Always1PageHorizontal270,
        Always1PageVertical,
        Always1PageVertical270
    };
    public enum ShortcutKey
    {
        NextPage,
        PrevPage,
        AdvanceOnePage,
        ChangeDispMode,
        Reload,

        ChangeDocumentDirection,
        Slideshow,
        ToggleFullscreen,
        OpenFolder,
        PreferenceDialog,

        Help,
        Zoom,
        ListViewMode,
        Max
    };
    public enum ItemSortOrder
    {
        NameAsc,
        NameDesc,
        LastUpdateTimeAsc,
        LastUpdateTimeDesc,
    };
    public struct Rgb
    {
        private byte r;
        public int Red { get { return r; } set { r = (byte)value; } }
        private byte g;
        public int Green { get { return g; } set { g = (byte)value; } }
        private byte b;
        public int Blue { get { return b; } set { b = (byte)value; } }
        public Rgb(int red, int green, int blue)
        {
            r = (byte)red;
            g = (byte)green;
            b = (byte)blue;
        }
        public System.Drawing.Color Color()
        {
            return System.Drawing.Color.FromArgb(0xff, r, g, b);
        }
        public void Set(System.Drawing.Color color)
        {
            r = color.R;
            g = color.G;
            b = color.B;
        }
    };

    public class UserPreference
    {
        public const int FormTimerIntervalMax = 64767;
        public const int CurrentVersion = 1;
        private int version;
        public int Version
        {
            get { return version; }
            set { version = value; }
        }
        private bool bOpenFolderWhenStartup;
        public bool OpenFolderWhenStartup {
            get { return bOpenFolderWhenStartup; }
            set { bOpenFolderWhenStartup = value; }
        }
        private string openFolderPath;
        public string OpenFolderPath
        {
            get { return openFolderPath; }
            set { openFolderPath = value; }
        }
        private bool bUseSpecifiedTmpFolder;
        public bool UseSpecifiedTmpFolder
        {
            get { return bUseSpecifiedTmpFolder; }
            set { bUseSpecifiedTmpFolder = value; }
        }
        private string tmpFolderPath;
        public string TmpFolderPath
        {
            get { return tmpFolderPath; }
            set { tmpFolderPath = value; }
        }
        private DocumentArrangeDirection documentArrangeDirection;
        public DocumentArrangeDirection DocumentArrangeDirectionProperty
        {
            get { return documentArrangeDirection; }
            set { documentArrangeDirection = value; }
        }
        private bool fullScreen;
        public bool FullScreen
        {
            get { return fullScreen; }
            set { fullScreen = value; }
        }
        private int thumbnailSize;
        public int ThumbnailSize
        {
            get { return thumbnailSize; }
            set { thumbnailSize = value; }
        }
        private int slideshowAdvanceMSec;
        public int SlideshowAdvanceMSec
        {
            get { return slideshowAdvanceMSec; }
            set { slideshowAdvanceMSec = value; }
        }
        private Rgb backColor;
        public Rgb BackColor
        {
            get { return backColor; }
            set { backColor = value; }
        }
        public void BackColorSet(System.Drawing.Color color)
        {
            backColor.Set(color);
        }
        private string[] shortcutKeys = new string[(int)ShortcutKey.Max];
        public string ShortcutKeyGet(ShortcutKey action)
        {
            return shortcutKeys[(int)action];
        }
        public string[] ShortcutKeys
        {
            get { return shortcutKeys; }
            set { shortcutKeys = value; }
        }

        private PageViewModeSelection pageViewModeSelection;
        public PageViewModeSelection PageViewModeSelectionProperty
        {
            get { return pageViewModeSelection; }
            set { pageViewModeSelection = value; }
        }

        private bool preloadAllImageInTheFolder;
        public bool PreloadAllImageInTheFolder
        {
            get { return preloadAllImageInTheFolder; }
            set { preloadAllImageInTheFolder = value; }
        }
        private bool displayStatusBar;
        public bool DisplayStatusBar
        {
            get { return displayStatusBar; }
            set { displayStatusBar = value; }
        }
        private System.Drawing.Drawing2D.InterpolationMode interpolationMode;
        public System.Drawing.Drawing2D.InterpolationMode InterpolationModeProperty
        {
            get { return interpolationMode; }
            set { interpolationMode = value; }
        }
        private System.Drawing.Drawing2D.InterpolationMode thumbnailInterpolationMode;
        public System.Drawing.Drawing2D.InterpolationMode ThumbnailInterpolationModeProperty
        {
            get { return thumbnailInterpolationMode; }
            set { thumbnailInterpolationMode = value; }
        }
        private bool displayNumberOfThumbnailImagesInFolderTree;
        public bool DisplayNumberOfThumbnailImagesInFolderTree
        {
            get { return displayNumberOfThumbnailImagesInFolderTree; }
            set { displayNumberOfThumbnailImagesInFolderTree = value; }
        }
        private ItemSortOrder folderSortOrder;
        public ItemSortOrder FolderSortOrder
        {
            get { return folderSortOrder; }
            set { folderSortOrder = value; }
        }
        private ItemSortOrder fileSortOrder;
        public ItemSortOrder FileSortOrder
        {
            get { return fileSortOrder; }
            set { fileSortOrder = value; }
        }
        private string thumbnailCacheFolder;
        public string ThumbnailCacheFolder
        {
            get { return thumbnailCacheFolder; }
            set { thumbnailCacheFolder = value; }
        }
        private System.Collections.Generic.List<string> bookmarkList = new System.Collections.Generic.List<string>();
        public string[] BookmarkList
        {
            get { return bookmarkList.ToArray(); }
            set
            {
                bookmarkList.Clear();
                bookmarkList.AddRange(value);
            }
        }
        public void BookmarkAdd(string path)
        {
            bookmarkList.Add(path);
        }
        public void BookmarkListClear()
        {
            bookmarkList.Clear();
        }

        public UserPreference()
        {
            Reset();
        }
        public void Reset()
        {
            OpenFolderWhenStartup = true;
            OpenFolderPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // "C:\\";
            DocumentArrangeDirectionProperty = DocumentArrangeDirection.RightToLeft;
            FullScreen = false;

            ThumbnailSize = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width / 12;
            if (ThumbnailSize < 32) {
                ThumbnailSize = 32;
            }
            SlideshowAdvanceMSec = 4000;
            backColor = new Rgb(240, 240, 240);

            shortcutKeys[(int)ShortcutKey.NextPage] = "Next";
            shortcutKeys[(int)ShortcutKey.PrevPage] = "PageUp";
            shortcutKeys[(int)ShortcutKey.AdvanceOnePage] = "A";
            shortcutKeys[(int)ShortcutKey.ChangeDispMode] = "G";
            shortcutKeys[(int)ShortcutKey.Reload] = "R";

            shortcutKeys[(int)ShortcutKey.ChangeDocumentDirection] = "D";
            shortcutKeys[(int)ShortcutKey.Slideshow] = "S";
            shortcutKeys[(int)ShortcutKey.ToggleFullscreen] = "F";
            shortcutKeys[(int)ShortcutKey.OpenFolder] = "O";
            shortcutKeys[(int)ShortcutKey.PreferenceDialog] = "P";

            shortcutKeys[(int)ShortcutKey.Help] = "F1";
            shortcutKeys[(int)ShortcutKey.Zoom] = "Z";
            shortcutKeys[(int)ShortcutKey.ListViewMode] = "Escape";

            PageViewModeSelectionProperty = PageViewModeSelection.AutoSelect;
            PreloadAllImageInTheFolder = false;
            DisplayStatusBar = true;
            InterpolationModeProperty = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            ThumbnailInterpolationModeProperty = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            thumbnailCacheFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + System.IO.Path.DirectorySeparatorChar + ".TwoPageView";
            displayNumberOfThumbnailImagesInFolderTree = true;
            folderSortOrder = ItemSortOrder.NameAsc;
            fileSortOrder = ItemSortOrder.NameAsc;
        }
        public string ShortcutKeyDisplayStringGet(ShortcutKey key)
        {
            string s = ShortcutKeyGet(key);
            return ShortcutKeyStringToShortcutKeyDisplayString(s);
        }
        public static string ShortcutKeyStringToShortcutKeyDisplayString(string skstr)
        {
            switch (skstr) {
            case "D0": return "0";
            case "D1": return "1";
            case "D2": return "2";
            case "D3": return "3";
            case "D4": return "4";

            case "D5": return "5";
            case "D6": return "6";
            case "D7": return "7";
            case "D8": return "8";
            case "D9": return "9";

            case "Next": return "PageDown";
            case "Back": return "BackSpace";
            default:
                return skstr;
            }
        }
        public static string ShortcutKeyDisplayStringToShortcutKeyString(string skdstr)
        {
            switch (skdstr) {
            case "0" : return "D0";
            case "1" : return "D1";
            case "2" : return "D2";
            case "3" : return "D3";
            case "4" : return "D4";

            case "5" : return "D5";
            case "6" : return "D6";
            case "7" : return "D7";
            case "8" : return "D8";
            case "9" : return "D9";

            case "PageDown": return "Next";
            case "BackSpace": return "Back";
            default: return skdstr;
            }
        }
        public void SetSlideshowAdvanceMSec(int msec)
        {
            if (msec < 1) {
                msec = 1;
            }
            if (FormTimerIntervalMax < msec) {
                msec = FormTimerIntervalMax;
            }
            SlideshowAdvanceMSec = msec;
        }
    }
    
    sealed class UserPreferenceIO
    {
        public static string fileName = "UserPreference.xml";
        private UserPreferenceIO()
        {
        }

        public static UserPreference LoadFromFile()
        {
            Console.WriteLine("D: LoadFromFile() {0}", fileName);
            System.Xml.Serialization.XmlSerializer formatter = 
                new System.Xml.Serialization.XmlSerializer(typeof(UserPreference));
            System.IO.IsolatedStorage.IsolatedStorageFileStream settingsFile;

            UserPreference up = new UserPreference();
            try {
                settingsFile = new System.IO.IsolatedStorage.IsolatedStorageFileStream(fileName,
                    System.IO.FileMode.Open,
                    System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForDomain());
            } catch (System.IO.FileNotFoundException ex) {
                Console.WriteLine(ex);
                return up;
            }

            {
                byte[] buffer = new byte[settingsFile.Length];
                settingsFile.Read(buffer, 0, (int)settingsFile.Length);
                System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer);
                up = formatter.Deserialize(stream) as UserPreference;
                settingsFile.Close();
            }
            bool bOK = UserPreference.CurrentVersion == up.Version;
            if ((int)ShortcutKey.Max != up.ShortcutKeys.Length) {
                bOK = false;
            } else {
                string[] shortcutKeys = up.ShortcutKeys;
                foreach (string s in shortcutKeys) {
                    if (0 == s.Length) {
                        bOK = false;
                    }
                }
            }
            if (!bOK) {
                Console.WriteLine("D: LoadFromFile() Default userPreference");
                return new UserPreference();
            }
            Console.WriteLine("D: LoadFromFile() Success");
            return up;
        }

        public static void SaveToFile(UserPreference userPreference)
        {
            Console.WriteLine("D: SaveToFile() {0}", fileName);
            System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(UserPreference));
            System.IO.IsolatedStorage.IsolatedStorageFileStream isfs =
                new System.IO.IsolatedStorage.IsolatedStorageFileStream(fileName,
                        System.IO.FileMode.Create,
                        System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForDomain());
            try {
                userPreference.Version = UserPreference.CurrentVersion;
                s.Serialize(isfs, userPreference);
            } catch (System.IO.IOException ex) {
                Console.WriteLine(ex.ToString());
            } finally {
                isfs.Close();
            }
        }
    }
}
